//
//  MYCustomLeftRightBtn.m
//  CapitalCycle
//
//  Created by 范名扬 on 15/3/2.
//  Copyright (c) 2015年 范名扬. All rights reserved.
//

#import "MYCustomLeftRightBtn.h"

@implementation MYCustomLeftRightBtn

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

- (void)setImage:(UIImage *)image forState:(UIControlState)state{
    [super setImage:image forState:state];
    
//    if (self.imageView.image) {
        // 图片保持原状居中
//        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        // 文字居中
//        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        // 设置字体
//        self.titleLabel.font = [UIFont systemFontOfSize:13];
//    }else{
//        self.titleLabel.textAlignment = NSTextAlignmentCenter;
//    }
}
- (void)setHighlighted:(BOOL)highlighted {
}

/**
 *  内部图片（左右格式）
 */
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    if (!self.currentTitle) {
        return [super imageRectForContentRect:contentRect];
    }
    // 设置属性
    CGFloat titleW = [self getTitleWidth];
    CGFloat imageW = 20;
    CGFloat imageH = 20;
    CGFloat totalW = titleW + 5 + imageW;
    CGFloat imageY = ((self.frame.size.height - imageH)/2 < 0)? 0 : (self.frame.size.height - imageH)/2;
    CGFloat imageX = (self.frame.size.width - totalW)/2 + titleW + 5;

    return CGRectMake(imageX, imageY, imageW, imageH);
}
/**
 *  内部文字
 */
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    if (!self.currentImage) {
        return [super titleRectForContentRect:contentRect];
    }
    
    // 属性
    CGFloat titleW = [self getTitleWidth];
    CGFloat totalW = titleW + 5 + 20;
    CGFloat titleX = (self.frame.size.width - totalW)/2;

    return CGRectMake(titleX, 0, titleW, self.frame.size.height);
}

- (CGFloat)getTitleWidth
{
    NSDictionary *dict = @{NSFontAttributeName: self.titleLabel.font};
    CGFloat titleW = [self.currentTitle boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size.width + 1;
    return titleW;
}

@end
